package com.example.justbuy.action.seller;



import com.example.justbuy.mapper.OrderMapper;
import com.example.justbuy.pojo.*;
import com.example.justbuy.service.ImageMapperService;
import com.example.justbuy.service.OrderMapperService;
import com.example.justbuy.service.StoreDaoService;
import com.example.justbuy.service.WorkflowService;
import com.example.justbuy.util.ConvertDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Controller
public class StoreAction {
    @Autowired
    private StoreDaoService storeDaoService;
    @Autowired
    private WorkflowService workflowService;
    @Autowired
    private ImageMapperService imageMapperService;
    @Autowired
     private OrderMapperService orderMapperService;


    /*
     * 跳转到商家入驻页面
     * @return
     * */
    @RequestMapping("/storein.htm")
    public String zhuce(Model md, HttpServletRequest request, HttpServletResponse response) {
        return "seller/regist1.html";
    }

    /*
     * 跳转到店铺管理页面
     * @return
     * */
    @RequestMapping("/storeinto.htm")
    public String storemagger(Model md,  HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute("user");
        int storeid = user.getStoreid();
       List<Store> list= storeDaoService.getAllStoreById(storeid);

        String  storeState=list.get(0).getStoreState();
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+storeState);
        if(storeState.equals("已通过")){
           Double allprice= storeDaoService.getAllPriceByStoreId(storeid);
            md.addAttribute("allprice", allprice);
            md.addAttribute("slist", list);
            md.addAttribute("storeid", storeid);
            return "seller/sellermine.html";
        }else {
            md.addAttribute("slist", list);
            return "seller/sellermineno.html";
        }



    }


    @RequestMapping("/success.htm")
    public String registl(String leganName, String leganCode, String companyName, String phone, String businessNum, String storeState, String bank, String bankCode, Model md, String gender, HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws Exception {

        /**
         * 保存图片
         */
        //保存图片根路径
        String pic_path = request.getSession().getServletContext().getRealPath("/");
        //获取文件原名称
        String originalFilename = file.getOriginalFilename();
        if (file != null && originalFilename != null && originalFilename.length() > 0) {
            //新的图片名称
            String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            md.addAttribute("newFileName",newFileName);
            //新建文件
            //File newFile = new File(pic_path + newFileName);
            File newFile = new File("/tmp/" + newFileName);
            //将图片写入文件中
            file.transferTo(newFile);
            HashMap map = new HashMap();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
            map.put("addTime", ConvertDateUtil.castDate(date));
            User user = (User) request.getSession().getAttribute("user");
            map.put("userId", Integer.valueOf(user.getId()));
            map.put("id", Integer.valueOf(user.getId()));
            map.put("path",newFileName);
            map.put("des","营业执照正本");
            int flag = imageMapperService.save(map);/*存入图片到图片表*/

            map.put("leganName", leganName);
            map.put("realname", leganName);//为修改用户表使用
            map.put("leganCode", leganCode);
            map.put("idCord", leganCode);//为修改用户表使用
            map.put("gender", gender);//为修改用户表使用
            map.put("roleid", "2");//为修改用户表使用
            map.put("bank", bank);//为修改用户表使用
            map.put("bankCode", bankCode);//为修改用户表使用
            map.put("companyName", companyName);
            map.put("phone", phone);
            map.put("businessNum", businessNum);
            map.put("storeState", storeState);
            int flag1 = storeDaoService.insertStore(map);/*数据存入店铺表*/
            if(flag1>0){
                int storeId = storeDaoService.getStoreIdBybusinessNum(businessNum);/*根据营业执照编码查询店铺ID*/

            map.put("storeId", storeId);
                int flag2 = storeDaoService.updateUser(map);
                if(flag2>0){
                   User uu= storeDaoService.getAlluser(Integer.valueOf(user.getId()));
                request.getSession().setAttribute("user",uu);


                    String did = workflowService.startProcessInstance();//*流程ID*//*

                    workflowService.updeAssignee(leganName, did);

                    String taskid = workflowService.getTaskid(did, "用户申请");

                    workflowService.completeTask(taskid, "入驻", map);
                return "seller/success.html";
                }

            }




        }
        return "seller/success.html";
    }


    /*
   * 异步查询营业执照代码是否已经被注册；
   * @return
   * */
    @RequestMapping("/businessNum.htm")
    public @ResponseBody
    String bunm(String businessNum) {
        List<Store> list = storeDaoService.getAllStoreBybusinessNum(businessNum);
        if (list.size() > 0) {
            return "1";
        } else {
            return "2";
        }
    }

    /*
  * 入驻页面前往入驻协议；
  * @return
  * */
    @RequestMapping("/xieyi1.htm")
    public String xieyi() {
        return "seller/xieyi.html";
    }

    /*
    * 点击头像根据ID获取店铺信息跳转页面
    * @return
    * */
    @RequestMapping("/storemessage.htm")
    public String Storemessage(String storeid, Model md, HttpServletRequest request, HttpServletResponse response) {
        List<Store> storeList = storeDaoService.getAllStoreById(Integer.valueOf(storeid));
        md.addAttribute("storeList", storeList);
        return "seller/storemessage.html";
    }

    /*
   * 点击店铺里的全部订单，根据店铺获ID全部订单信息
   * @return
   * */
    @RequestMapping("/store_all_orders.htm")
    public String allOrederform( Model md, HttpServletRequest request, HttpServletResponse response) {
        HashMap map = new HashMap();
        User user = (User) request.getSession().getAttribute("user");
        int storeid = user.getStoreid();
        map.put("storeId",storeid);
        map.put("orderState","已付款");
        int userid=user.getId();
        List<Order> orderList = storeDaoService.getGoodsOrderByStoreId(storeid);
        List<Order> Statelist =storeDaoService.getGoodsOrderByorderState(map);

        md.addAttribute("list", orderList);
        md.addAttribute("list1", Statelist);
        md.addAttribute("userid", userid);
        return "seller/store_all_orders.html";
    }

    /*
    * 点击店铺里我的银行卡，根据店铺id获取该店铺所添加的银行卡信息；
    * @return
    * */
    @RequestMapping("/card.htm")
    public String allBank(Model md, HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute("user");
        int storeid = user.getStoreid();
        List<Store> bankList = storeDaoService.getBankById(storeid);
        md.addAttribute("bankList", bankList);
        return "seller/card.html";
    }

    /*
     * 在我的银行卡点击添加或修改，进入添加或修改页面 并把店铺ID带过去；
     * @return
     * */
    @RequestMapping("/add_card.htm")
    public String addcard(Model md, HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute("user");
        int storeid = user.getStoreid();
        md.addAttribute("id", storeid);
        return "seller/add_card.html";
    }

    /*
      * 根据店铺ID修改银行卡信息；
      * @return
      * */
    @RequestMapping("/banksuccess.htm")
    public String updateBankCode(String bank, String bankCode, String phone, String idname, Model md, HttpServletRequest request, HttpServletResponse response) {
        HashMap map = new HashMap();
        map.put("bank", bank);
        map.put("bankCode", bankCode);
        map.put("idname", Integer.valueOf(idname));
        map.put("phone", phone);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
        map.put("addTime", ConvertDateUtil.castDate(date));
        int flag = storeDaoService.updateBankcode(map);
        if (flag > 0) {
            return "seller/banksuccess.html";
        }
        return "seller/success.html";
    }

    /*
     * 在店铺管理里点击交易记录 获取交易记录；
     * @return
     * */
    @RequestMapping("/record.htm")
    public String jiaoyi( Double allprice,Model md, HttpServletRequest request, HttpServletResponse response) {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+allprice);
        User user = (User) request.getSession().getAttribute("user");
        int storeId = user.getStoreid();
        HashMap map = new HashMap();
        map.put("orderState","已完成");
        map.put("storeId",storeId);
       List<Order> orderList= storeDaoService.getAll0rderBypay(map);
          if(allprice==null){
             allprice=0.00;
             md.addAttribute("orderList",orderList);
              md.addAttribute("allprice",0.00);
          }else{
              md.addAttribute("allprice",allprice);
              md.addAttribute("orderList",orderList);
          }
        return "seller/record.html";
    }

    /*
   * 在店铺管理里点击宝贝管理 去到商品管理页面；
   * @return
   * */
    @RequestMapping("/Goods.htm")
    public String baobei(Model md, HttpServletRequest request, HttpServletResponse response) {
       User user = (User) request.getSession().getAttribute("user");
       int storeid = user.getStoreid();
        List<Goods> Goodslist = storeDaoService.getAllGoodsByStoreId(storeid);
        md.addAttribute("Goodslist", Goodslist);
        return "seller/Goods.html";
    }

    /*
  * 点击宝贝管理里的添加商品  去到添加商品页面；
  * @return
  * */
    @RequestMapping("/GoodsEditor.htm")
    public String addbb(Model md, HttpServletRequest request, HttpServletResponse response) {
//        User user = (User) request.getSession().getAttribute("user");
//        int storeid = user.getStoreid();
        UUID goodsCode = UUID.randomUUID();
       md.addAttribute("goodsCode",goodsCode);
        return "seller/GoodsEditor.html";
    }

    /*
  * 保存商品到工作流；
  * @return
  * */
    @RequestMapping("/saveGoods.htm")
    public String saveGoods(MultipartFile path, String goodsName, Double price, String goodsDsc, Integer repertory, String goodsState,String goodsCode, Model md, HttpServletRequest request, HttpServletResponse response) throws Exception {//        int storeid = user.getStoreid();
        /**
         * 保存图片
         */
        //保存图片根路径
        String pic_path = request.getSession().getServletContext().getRealPath("/");
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>1112"+pic_path);
        //获取文件原名称
        String originalFilename = path.getOriginalFilename();
        if (path != null && originalFilename != null && originalFilename.length() > 0) {
            //新的图片名称
            String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            //新建文件
            //File newFile = new File(pic_path + newFileName);
            File newFile = new File("/tmp/" + newFileName);
            //将图片写入文件中
            path.transferTo(newFile);
            HashMap map = new HashMap();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
            map.put("addtime", ConvertDateUtil.castDate(date));
            map.put("path", newFileName);
            User user = (User) request.getSession().getAttribute("user");
            map.put("storeId",Integer.valueOf(user.getStoreid()));

            map.put("userId", Integer.valueOf(user.getId()));
            map.put("des", goodsDsc);
           List<Store> list= storeDaoService.getAllStoreById(Integer.valueOf(user.getStoreid()));
            String realName=list.get(0).getLeganName();
            String  companyName=list.get(0).getCompanyName();
            map.put("companyName",companyName);
            int flag = imageMapperService.save(map);/*存入图片到图片表*/
            int imgid=0;
            if (flag > 0) {
               imgid = imageMapperService.getImageIdByImagePath(newFileName);/*根据路径查图片ID*/

                map.put("imageid",imgid);
            }
            map.put("goodsName", goodsName);
            map.put("price", price);
            map.put("goodsDsc", goodsDsc);
            map.put("repertory", repertory);
            map.put("goodsState", goodsState);
            map.put("goodsCode",goodsCode);
            int fg=storeDaoService.addGoods(map);
            Goods gd=storeDaoService.getBygoodsCode(goodsCode);
            HashMap map06 = new HashMap();
            map06.put("goodsId",Integer.valueOf(gd.getId()));
            map06.put("imgid",Integer.valueOf(imgid));
            int flag06=imageMapperService.updateGoodsId(map06);
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>商品图片保存"+flag06);
            if(fg>0){
                String did = workflowService.startProcessInstance();//*流程ID*//*
                workflowService.updeAssignee(realName, did);
                String taskid = workflowService.getTaskid(did, "用户申请");

                workflowService.completeTask(taskid, "商品", map);

                return "seller/banksuccess.html";
            }


        }
        return "seller/banksuccess.html";
    }
     /*
  * 首页转发；
  * @return
  * */
    @RequestMapping("/index.htm")

    public  String zhuanfa(){

        return "redirect:/";
    }

    /*
* 违规记录转发；
* @return
* */
    @RequestMapping("/weigui.htm")

    public  String weigui(){

        return "seller/weigui.html";
    }

    /*
* 点击发货 去到发货页面
* @return
* */
    @RequestMapping("/address.htm")

    public  String fahuo(String orderId ,Model md){
       List<Order> orderList= storeDaoService.getUserid(orderId);
       System.out.println(">>>>>>>>>>>>>>>>>>"+orderList.get(0).getUserId());
        String address=orderList.get(0).getAddress();

        List<Address> addressList= storeDaoService.getAddressByaddress(address);

        md.addAttribute("orderList",orderList);
        md.addAttribute("addressList",addressList);

        return "seller/address.html";
    }
        /*
* 点击发货 去到发货页面
* @return
* */
        @RequestMapping("/fahuosuccess.htm")

        public  String fahuosuccess(String orderId ,Model md){
            HashMap map = new HashMap();
            map.put("orderId",orderId);
            map.put("orderState","已发货");
           int flag= orderMapperService.updateStateById(map);
            return "seller/fahuosuccess.html";
        }

    /*
* 小金库转发；
* @return
* */
    @RequestMapping("/xioajinku.htm")

    public  String xiaojinku(){

        return "seller/xioajinku.html";
    }
}
